package com.example.king.openglenvdemo;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

import com.example.king.glutils.GlesUtil;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT;
import static android.opengl.GLES20.glClear;
import static android.opengl.GLES20.glClearColor;
import static android.opengl.GLES20.glDrawArrays;
import static android.opengl.GLES20.glGetAttribLocation;
import static android.opengl.GLES20.glUseProgram;
import static android.opengl.GLES20.glVertexAttrib3f;
import static android.opengl.GLES20.glViewport;

/**
 * 画多个点
 */
public class MultiPointRenderer implements GLSurfaceView.Renderer {

    private final String mVertexShader =
            "attribute vec4 aPosition;\n" +
            "void main() {\n" +
            "  gl_Position = aPosition;\n" +
            "  gl_PointSize = 30.0;\n" +
            "}\n";

    private final String mFragmentShader =
            "void main() {\n" +
            "  gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n" +
            "}\n";

    private int mProgram;

    private int maPositionHandle;

    private final int FLOAT_SIZE_BYTES = 4;

    private final float[] mPointVerticesData = {
            0.0f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f
    };

    private FloatBuffer mTriangleVertices;

    public MultiPointRenderer() {
        mTriangleVertices = ByteBuffer.allocateDirect(mPointVerticesData.length * FLOAT_SIZE_BYTES)
        .order(ByteOrder.nativeOrder())
        .asFloatBuffer();
        mTriangleVertices.put(mPointVerticesData).position(0);
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        mProgram = GlesUtil.linkProgram(mVertexShader, mFragmentShader);
        glUseProgram(mProgram);

        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

        maPositionHandle = glGetAttribLocation(mProgram, "aPosition");
        GlesUtil.catchError("aPosition");

        mTriangleVertices.position(0);
        GLES20.glVertexAttribPointer(maPositionHandle, 2, GLES20.GL_FLOAT, false,
                2 * FLOAT_SIZE_BYTES, mTriangleVertices);

        GLES20.glEnableVertexAttribArray(maPositionHandle);
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GLES20.GL_POINTS, 0, 3);
    }
}
